<template>
  <div id="indexMap-map" style="width:100%;height:100%"></div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import { getProjection,getChinaBaseLayer3857 } from "@/map/projMap.js";
import { fromLonLat, toLonLat, transform } from "ol/proj";
import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source';
import WKT from 'ol/format/WKT';
import {boundingExtent} from 'ol/extent';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';
import yellowCircleSmall from '@/assets/map/image/newImage/yellowCircleSmall.png';
import * as turf from '@turf/turf';

export default {
  name: "IndexMap",
  components: {

  },
  props:{

  },
  emits:["getMap"],
  data() {
    return {
      str: "indexMap",
      map: null,
      // center: [105, 34],
      // zoom: 4,
      // center: [105, 27.5],
      center: fromLonLat([105, 27.5]),//4490转3857坐标系
      zoom: 4,
      //大屏首页城市弧线动画
      provinceCenterList:[],//省份中心点数据列表
      xianCityLineList:[],//省份中心点西安弧线数据列表
      xianCityLineAllLonLatList:[],//省份中心点西安弧线经纬度数据列表
      xianCityLinePointList:[],//省份中心点西安弧线动画点数据列表
      provinceCityPointLayer:null,//省份中心点图层
      xianCityLineLayer:null,//西安弧线图层
      xianCityLinePointLayer:null,//西安弧线动画点图层
      currentXianCityLinePointIndex:0,//动画点序号
    }
  },
  watch: {

  },
  created() {

  },
  mounted() {
    console.log("mounted");
    let that = this;
    //地图异步加载
    this.$nextTick(function(){
      console.log('地图异步加载');
      //地图异步加载
      setTimeout(() => {
        //初始化地图信息
        that.initMap();
        //根据省份中心点数据列表获取弧线
        that.getAllProvinceCenterLineList();
        //显示省中心点图层
        that.showProvinceCityPointLayer();
        //显示西安弧线图层
        that.showXianCityLineLayer();
        //显示西安弧线点动画
        that.showXianCityLinePointInterval();
      }, 200);
    });
  },
  beforeCreate() {//生命周期创建之前
    console.log("beforeCreate");
  },
  beforeMount() {//生命周期挂载之前
    console.log("beforeMount");
  },
  beforeUpdate() {//生命周期更新之前
    console.log("beforeUpdate");
  },
  updated() {//生命周期更新之后
    console.log("updated");
  },
  beforeDestroy() {//生命周期销毁之前
    console.log("beforeDestroy");
  },
  destroyed() {//生命周期销毁完成
    this.map = null;
    console.log("销毁地图");
  },
  activated() {//如果页面有keep-alive缓存功能激活，这个函数会触发
    console.log("activated-"+this.str);
    //自动获取地图div高度
    this.autodivheight();
    //浏览器窗口发生变化时同时变化DIV高度
    // window.onresize=this.autodivheight;
  },
  deactivated() {//如果页面有keep-alive缓存功能停用，这个函数会触发
    console.log("deactivated-"+this.str);
    //取消浏览器窗口发生变化时同时变化DIV高度事件
    // window.onresize = null;
  },
  methods: {
    initMap() {
      // debugger;
      let that = this;
      let mapStr = this.str;
      let targetMap = document.getElementById(mapStr+"-map");
      if(targetMap.innerHTML!=""){
        console.log("清空targetMap");
      }
      targetMap.innerHTML = "";//清空
      //自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      // window.onresize=this.autodivheight;
      if(this.map){//避免重复加载地图
        console.log("避免重复加载地图");
        return;
      }
      console.log("初始化地图");
      //获取投影4490坐标系
      // this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        /*controls: defaultControls({attributionOptions: {collapsed: false}})
            .extend([new Logo()]),*/
        view: new View({
          center: this.center,
          // maxZoom: 18,
          // minZoom: 3,
          maxZoom: this.zoom,
          minZoom: this.zoom,
          zoom: this.zoom,
          constrainResolution:true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
          // projection: 'EPSG:4490',
          projection: 'EPSG:3857',
          // resolutions:getResolutions()
        })
      });
      console.log("this.map");
      console.log(this.map);

      //添加超图中国地图蓝色3857
      getChinaBaseLayer3857(this.map);

      //省中心点图层
      this.provinceCityPointLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        // projection: 'EPSG:4490'
        projection: 'EPSG:3857',
      });
      this.map.addLayer(this.provinceCityPointLayer);
      this.provinceCityPointLayer.setZIndex(9);

      //西安弧线图层
      this.xianCityLineLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        // projection: 'EPSG:4490'
        projection: 'EPSG:3857',
      });
      this.map.addLayer(this.xianCityLineLayer);
      this.xianCityLineLayer.setZIndex(8);

      //西安弧线动画点图层
      this.xianCityLinePointLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        // projection: 'EPSG:4490'
        projection: 'EPSG:3857',
      });
      this.map.addLayer(this.xianCityLinePointLayer);
      this.xianCityLinePointLayer.setZIndex(8);

      // 这里是将所有交互都关闭了，可以选择只关闭鼠标，虽然效果不好
      this.map.getInteractions().forEach(element => {
        element.setActive(false)//false禁止拖拽，true允许拖拽
      });

      //地图对象传递
      this.$emit("getMap",this.map);
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:680px
      let tempHeight = 864;
      let mapTempHeight = 740;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      /*//最小高度
      if(mapHeight<480){
        mapHeight = 480;
      }*/
      //设置地图高度
      document.getElementById(this.str+"-map").style.height= mapHeight +"px";
      console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
    getPointStyle(){// 点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          anchor: [0.5, 1]
        }),
      });
      return style;
    },
    getProvinceCityPointStyle(type){//省中心点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          anchor: [0.5, 1]
        }),
      });
      if(type=="large"){
        style = new Style({
          image: new Icon({
            src: yellowCircleSmall,
            scale:0.6,
          }),
        });
      }else if(type=="small"){
        style = new Style({
          image: new Icon({
            src: yellowCircleSmall,
            scale:0.4,
          }),
        });
      }else if(type=="point"){
        style = new Style({
          image: new Icon({
            src: yellowCircleSmall,
            scale:0.1,
          }),
        });
      }
      return style;
    },
    getLineStringStyle(color,fillColor,width){//线样式
      if(fillColor!=null){
        //填充样式
      }else{
        fillColor = "rgba(0,0,0,0)";
      }
      if(width!=null){
        //线宽度
      }else{
        width = 2;
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:fillColor
        }),
        stroke:new Stroke({//描绘
          width:width,//宽
          color:color
        }),
        zIndex: 100
      });
      return style;
    },
    getPolyonStyle(color,fillColor,width){//多边形样式
      if(fillColor!=null){
        //填充样式
      }else{
        fillColor = "rgba(0,0,0,0)";
      }
      if(width!=null){
        //线宽度
      }else{
        width = 2;
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:fillColor
        }),
        stroke:new Stroke({//描绘
          width:width,//宽
          color:color
        }),
        zIndex: 100
      });
      return style;
    },
    getSelectPolyonStyle(){//选中要素样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(255,255,255,0.2)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:"rgba(30,144,255,1)"
        })
      });
      return style;
    },
    showBoundingExtent(coordinates){//缩放到区域位置
      console.log("缩放到区域位置");
      if (coordinates!=null && coordinates.length > 1) {
        const extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
        //获取默认位置
        this.center = this.map.getView().getCenter();
        this.zoom = this.map.getView().getZoom();
      }
    },
    //根据省份中心点数据列表获取弧线
    getAllProvinceCenterLineList(){
      let list = [
        {name:"北京市",geom:"POINT(116.41257667603315 40.185597596456724)"},
        {name:"天津市",geom:"POINT(117.33236420715916 39.293252161581435)"},
        {name:"河北省",geom:"POINT(116.13550644299869 39.54842509298008)"},
        {name:"山西省",geom:"POINT(112.28955886230568 37.57193255811226)"},
        {name:"内蒙古自治区",geom:"POINT(113.72252599477328 43.96484764957964)"},
        {name:"辽宁省",geom:"POINT(122.60008499528848 41.28435612266014)"},
        {name:"吉林省",geom:"POINT(126.1711017783561 43.663994232027655)"},
        {name:"黑龙江省",geom:"POINT(127.64888013089549 47.973721105579884)"},
        {name:"上海市",geom:"POINT(121.44495128770177 31.19134082856172)"},
        {name:"江苏省",geom:"POINT(119.47653999045788 32.96421737397533)"},
        {name:"浙江省",geom:"POINT(120.16864156077324 29.178022230878337)"},
        {name:"安徽省",geom:"POINT(117.22639824941024 31.8259918399844)"},
        {name:"福建省",geom:"POINT(117.99524171127864 26.073368521546424)"},
        {name:"江西省",geom:"POINT(115.72219237052809 27.614081943378128)"},
        {name:"山东省",geom:"POINT(118.15621304185623 36.35154198911674)"},
        {name:"河南省",geom:"POINT(113.61398718717692 33.881939562224545)"},
        {name:"湖北省",geom:"POINT(112.27151168194709 30.975460718134162)"},
        {name:"湖南省",geom:"POINT(111.70890526762348 27.609875655786244)"},
        {name:"广东省",geom:"POINT(113.41657642543589 23.33437847086625)"},
        {name:"广西壮族自治区",geom:"POINT(108.78816315046072 23.825532912381906)"},
        {name:"海南省",geom:"POINT(109.77919647976503 19.1568199219241)"},
        {name:"重庆市",geom:"POINT(107.874515382819 30.05718447181117)"},
        {name:"四川省",geom:"POINT(102.6929232671575 30.629247817816108)"},
        {name:"贵州省",geom:"POINT(106.87498742377443 26.815420552356912)"},
        {name:"云南省",geom:"POINT(101.4868527344774 24.974994855751024)"},
        {name:"西藏自治区",geom:"POINT(88.44150852461733 31.490830787202775)"},
        {name:"陕西省",geom:"POINT(108.8689274864618 35.19107483451537)"},
        // {name:"甘肃省",geom:"POINT(100.604104043659 37.88149179793797)"},
        {name:"青海省",geom:"POINT(96.03936757225128 35.67066041281156)"},
        {name:"宁夏回族自治区",geom:"POINT(106.16381361020456 37.27150346346491)"},
        // {name:"新疆维吾尔自治区",geom:"POINT(85.18960522587882 41.116596840946634)"},
        {name:"新疆维吾尔自治区",geom:"POINT(86.16125020794858 41.739967029712105)"},
        {name:"台湾省",geom:"POINT(120.96733849875879 23.747652555878208)"},
        {name:"香港特别行政区",geom:"POINT(114.13408649973996 22.38163276220061)"},
        {name:"澳门特别行政区",geom:"POINT(113.55937121792418 22.16005152988829)"},
          //加点
        {name:"乌鲁木齐市",geom:"POINT(87.60148659335314 43.8381745254147)"},
        {name:"吐鲁番市",geom:"POINT(89.76996353466858 42.38323628667799)"},
        {name:"哈密市",geom:"POINT(93.50061479747237 42.837909409332205)"},
        {name:"阿克苏市",geom:"POINT(80.25725876186229 41.18351086347508)"},
        {name:"和田市",geom:"POINT(79.90898749711418 37.1401083311644)"},
        {name:"喀什市",geom:"POINT(75.97217216271008 39.49346450728832)"},
        {name:"拉萨市",geom:"POINT(91.10300349341844 29.686042202725258)"},
        {name:"日喀则市",geom:"POINT(88.87002711540181 29.286023523523614)"},
        {name:"阿里地区",geom:"POINT(82.06887569121056 33.26542063342275)"},
        {name:"那曲市",geom:"POINT(92.02460373343095 31.51448590506713)"},
        {name:"林芝市",geom:"POINT(94.35435985959008 29.676727967040982)"},
        {name:"呼和浩特市",geom:"POINT(111.70685247826357 40.87564116380755)"},
        {name:"乌兰察布市",geom:"POINT(113.1012070238536 41.013696069311514)"},
        {name:"包头市",geom:"POINT(109.82930576340968 40.668558805551605)"},
        {name:"巴彦淖尔市",geom:"POINT(107.37192844543912 40.76519723940438)"},
        {name:"锡林浩特市",geom:"POINT(116.06938749218882 43.968071047096345)"},
        {name:"赤峰市",geom:"POINT(118.86291471786876 42.2744008758393)"},
        {name:"呼伦贝尔市",geom:"POINT(119.7484745679032 49.2440848807401)"},
        {name:"乌海市",geom:"POINT(106.76448686122168 39.67456348592307)"},
        {name:"西宁市",geom:"POINT(101.76689928197821 36.63735556483587)"},
        {name:"兰州市",geom:"POINT(103.81011188343687 36.08513594282002)"},
        {name:"武威市",geom:"POINT(102.62283969610279 37.94887716712353)"},
        {name:"嘉峪关市",geom:"POINT(98.27411017272794 39.798812900876634)"},
        {name:"齐齐哈尔市",geom:"POINT(123.89748645787944 47.37456964177847)"},
        {name:"丽江市",geom:"POINT(100.20498219583703 26.878105365598344)"},
        {name:"哈尔滨市",geom:"POINT(126.4840401445712 45.81569877097543)"},
      ];
      //省份中心点数据列表
      this.provinceCenterList = list;
      //省份中心点西安弧线经纬度数据列表
      this.xianCityLineAllLonLatList = [];
      //省份中心点西安弧线数据列表
      let lineList = [];
      let xianGeom = "POINT(108.8689274864618 35.19107483451537)";
      let startLonLat = this.getLonLatByPointGeom(xianGeom);
      for(let i=0;i<list.length;i++){
        let data = list[i];
        let province = data.name;
        if(province=="陕西省"){
          continue;
        }
        let pointGeom = data.geom;
        let endLonLat = this.getLonLatByPointGeom(pointGeom);
        //获取弧线
        let lineGeom = this.getCurveLineByPoints(startLonLat,endLonLat);
        lineList.push({name:data.name,geom:lineGeom});
      }
      this.xianCityLineList = lineList;
    },
    getLonLatByPointGeom(geom){
      let lonlat = null;
      lonlat = geom.split("POINT(")[1].split(")")[0].split(" ");

      return lonlat;
    },
    //获取弧线
    getCurveLineByPoints(startLonLat,endLonLat){
      let start = turf.point(startLonLat);
      let end = turf.point(endLonLat);
      //获取弧线
      let greatCircle = turf.greatCircle(start, end, {'name': 'Seattle to DC'});
      // console.log("greatCircle");
      // console.log(greatCircle);
      let lonlatList = [];
      let geomText = "LineString(";
      let coordinates = greatCircle.geometry.coordinates;
      for(let i=0;i<coordinates.length;i++){
        if(i>0){
          geomText += ",";
        }
        let lonlat = coordinates[i];
        geomText += lonlat[0]　+ " " + lonlat[1];
        lonlatList.push(lonlat);
      }
      geomText += ")";
      this.xianCityLineAllLonLatList.push(lonlatList);

      return geomText;
    },
    //显示省中心点图层
    showProvinceCityPointLayer(){
      if(this.provinceCityPointLayer!=null){
        this.provinceCityPointLayer.getSource().clear();//清空
        let list = this.provinceCenterList;
        if(list!=null && list.length>0){
          for(let i=0;i<list.length;i++){
            let style = this.getProvinceCityPointStyle("small");//省中心点图标样式
            let name = list[i].name;
            if(name=="陕西省"){
              style = this.getProvinceCityPointStyle("large");//省中心点图标样式
            }
            let geomText = list[i].geom;
            if(geomText!=null && geomText!=""){
              //空间数据
              let featureTmp = new WKT().readFeature(geomText, {
                dataProjection: 'EPSG:4326', //	原坐标系
                featureProjection: 'EPSG:3857'// 转换坐标系
              });
              //设置属性
              featureTmp.setProperties({
                name:name,//名称
              });
              featureTmp.setStyle(style);
              //添加矢量数据
              this.provinceCityPointLayer.getSource().addFeature(featureTmp);
            }
          }
        }
      }
    },
    //显示西安弧线图层
    showXianCityLineLayer(){
      if(this.xianCityLineLayer!=null){
        this.xianCityLineLayer.getSource().clear();//清空
        let list = this.xianCityLineList;
        if(list!=null && list.length>0){
          for(let i=0;i<list.length;i++){
            let style = this.getLineStringStyle("yellow","yellow",1);
            let name = list[i].name;
            let geomText = list[i].geom;
            if(geomText!=null && geomText!=""){
              //空间数据
              let featureTmp = new WKT().readFeature(geomText, {
                dataProjection: 'EPSG:4326', //	原坐标系
                featureProjection: 'EPSG:3857'// 转换坐标系
              });
              //设置属性
              featureTmp.setProperties({
                name:name,//名称
              });
              featureTmp.setStyle(style);
              //添加矢量数据
              this.xianCityLineLayer.getSource().addFeature(featureTmp);
            }
          }
        }
      }
    },
    //显示西安弧线点动画
    showXianCityLinePointInterval(){
      let that = this;
      setTimeout(function(){
        let list = [];
        let index = that.currentXianCityLinePointIndex;//动画点序号
        let allLonLatList = that.xianCityLineAllLonLatList;//省份中心点西安弧线经纬度数据列表
        for(let i=0;i<allLonLatList.length;i++){
          let LonLatList = allLonLatList[i];
          if(index<LonLatList.length){
            let lonlat = LonLatList[index];
            let geom = "POINT(" + lonlat[0] + " " + lonlat[1] + ")";
            list.push(geom);
          }
        }
        that.xianCityLinePointList = list;//省份中心点西安弧线动画点数据列表;
        //西安弧线动画点图层
        that.showXianCityLinePointLayer();
        index++;
        if(index>=100){
          index = 0;
        }
        that.currentXianCityLinePointIndex = index;
        //显示西安弧线点动画
        that.showXianCityLinePointInterval();
      },30);
    },
    //西安弧线动画点图层
    showXianCityLinePointLayer(){
      if(this.xianCityLinePointLayer!=null){
        this.xianCityLinePointLayer.getSource().clear();//清空
        let list = this.xianCityLinePointList;//省份中心点西安弧线动画点数据列表
        if(list!=null && list.length>0){
          for(let i=0;i<list.length;i++){
            let style = this.getProvinceCityPointStyle("point");//动画点图标样式
            let geomText = list[i];
            if(geomText!=null && geomText!=""){
              //空间数据
              let featureTmp = new WKT().readFeature(geomText, {
                dataProjection: 'EPSG:4326', //	原坐标系
                featureProjection: 'EPSG:3857'// 转换坐标系
              });
              featureTmp.setStyle(style);
              //添加矢量数据
              this.xianCityLinePointLayer.getSource().addFeature(featureTmp);
            }
          }
        }
      }
    },
  }
}

</script>

<style lang="scss" scoped>

</style>